package com.example.myactspringboot.util;

/**
 * @Create 2023-10-01 08:57
 * @Description
 */

import javax.crypto.Cipher;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import org.apache.commons.codec.binary.Base64;
import java.util.HashMap;
import java.util.Map;

public class RSAUtils {
    public static Map<String ,String > keyMap =new HashMap<>();


    public static void main(String[] args) {
        RSAUtils rsaUtils = new RSAUtils();
        try {
            rsaUtils.getKeyPair();
            System.out.println(rsaUtils.keyMap.get("publicKey"));
            System.out.println(rsaUtils.keyMap.get("privateKey"));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }


    }

    public static void getKeyPair() throws NoSuchAlgorithmException {
        if (keyMap.isEmpty()){
            KeyPairGenerator pairGenerator =KeyPairGenerator.getInstance("RSA");

            pairGenerator.initialize(1024,new SecureRandom());
            KeyPair keyPair =pairGenerator.generateKeyPair();
            //生成公钥和密钥
            RSAPrivateKey privateKey =(RSAPrivateKey) keyPair.getPrivate();
            RSAPublicKey publicKey =(RSAPublicKey) keyPair.getPublic();
            keyMap.put("publicKey",new String(java.util.Base64.getEncoder().encode(publicKey.getEncoded())));
            keyMap.put("privateKey",new String(java.util.Base64.getEncoder().encode(privateKey.getEncoded())));
        }


    }

    public static String descry(String str) throws Exception {
        byte[] miBytes = Base64.decodeBase64(str.getBytes("UTF-8"));
        String privateKey = RSAUtils.keyMap.get("privateKey");
        byte[] privateKeyByte = Base64.decodeBase64(privateKey);

        RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(privateKeyByte));

        Cipher cipher =Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE,rsaPrivateKey);

        byte[] bytes = cipher.doFinal(miBytes);
        byte[] passbyte = Base64.decodeBase64(bytes);
        String s = new String(passbyte);
        return s;
    }
}
